import axios from 'axios';
import type { InternalAxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
import { mockResponses } from '@/mocks';

// 模拟数据配置
const mockConfig = {
  enabled: import.meta.env.VITE_USE_MOCK === 'true',
  delay: 300, // 模拟网络延迟(ms)
};

// 创建Axios实例
const api = axios.create({
  //baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
});

// 请求拦截器
api.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 可以在这里添加认证token等
    const token = localStorage.getItem('token');
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    // 统一处理响应数据
    return response.data;
  },
  (error: AxiosError) => {
    // 统一处理错误
    console.error('API Error:', error);
    if (error.response?.status === 401) {
      // 处理未授权错误，如重定向到登录页
      //window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// 封装常用请求方法
export const apiService = {
  get: <T>(url: string, params?: any, config?: InternalAxiosRequestConfig): Promise<T> => {
    if (mockConfig.enabled) {
        //使用模拟数据
        const mockResponse= url ? mockResponses[url] : undefined;
        if(mockResponse){
            return new Promise((resolve) => {
              setTimeout(() => {
                console.log('Mock data returned for', url, ':', mockResponse);
                resolve(mockResponse,);
              }, mockConfig.delay);
            });
        }
    }
    if(params){
        return api.get(url,params);
    }

    return api.get(url, config)
  },
  post: <T>(url: string, data?: any, config?: InternalAxiosRequestConfig): Promise<T> => api.post(url, data, config),
  put: <T>(url: string, data?: any, config?: InternalAxiosRequestConfig): Promise<T> => api.put(url, data, config),
  delete: <T>(url: string, config?: InternalAxiosRequestConfig): Promise<T> => api.delete(url, config),
  patch: <T>(url: string, data?: any, config?: InternalAxiosRequestConfig): Promise<T> => api.patch(url, data, config),
  uploadFile: <T>(url: string, data: FormData, config?: InternalAxiosRequestConfig): Promise<T> => {
    return api.post(url, data, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
};

export default api;